<?php
/**
 * Created by PhpStorm.
 * User: Merdan
 * Date: 2017/3/28
 * Time: 14:37
 */

namespace App\Http\Controllers;


use App\Exceptions\BaseException;
use App\Http\Requests\RecordRequest;
use App\Services\Record;
use Illuminate\Http\Request;

class RecordController extends Controller
{
    protected $recordService;

    function __construct()
    {
        parent::__construct();
        $this->recordService = new Record();
    }

    /**
     * 记录列表
     *
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        try {
            $limit = intval($request->get('count', 12));
            $filter = $request->get('filter');
            $records = $this->recordService->getList($limit, $filter);
            return $this->success('', $records);
        } catch (BaseException $e) {
            return $this->fail($e->getMessage());
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 获取单个记录信息
     *
     * @param $id
     * @return array
     */
    public function show($id)
    {
        try {
            $id = intval($id);
            $record = $this->recordService->show($id);
            return $this->success('', $record);
        } catch (BaseException $e) {
            return $this->fail($e->getMessage());
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }

    /**
     * 新增记录
     *
     * @param RecordRequest $request
     * @return array
     */
    public function store(RecordRequest $request)
    {
        try {
            $sku_id = intval($request->get('sku_id', 0));
            $type = intval($request->get('type', 0));
            $quantity = intval($request->get('quantity', 0));
            $notes = trim($request->get('notes', ''));
            $this->recordService->create(compact('sku_id', 'quantity', 'type', 'notes'));
            return $this->success('新增记录成功!');

        } catch (BaseException $e) {
            return $this->fail($e->getMessage());
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->fail('发生意外错误, 请稍后重试!');
        }
    }
}